<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.search" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getListDatas">查询 </el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="datas" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
 
 			<template v-for="(field,index) in typeInfos[$route.name]['fields']">
 				<template v-if="index < typeInfos[$route.name]['maxField']">
	 				<template v-if="field.relationModel!=''">
						<el-table-column v-bind:prop="field.relationModel+'-'+field.name" :label="field.showName" :formatter="formatFun" sortable >
						</el-table-column>
					</template>
					<template v-if="field.relationModel==''">
						<el-table-column :prop="field.name" :label="field.showName" sortable >
						</el-table-column>
					</template>
				</template>
			</template>
			
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			
			<el-form label-width="120px" :rules="editFormRules">
				<template v-for="field in updateTypeInfoForm">
					<template v-if="(field.compnent=='input')">
						<template v-if="(field.name=='id')">
							<el-form-item :label="field.label"  >
								<el-input v-model="field.value" auto-complete="off"></el-input>
							</el-form-item>
						</template>
						<template v-if="(field.name!='id')">
							<el-form-item :label="field.label"  >
								<el-input v-model="field.value" auto-complete="off"></el-input>
							</el-form-item>
						</template>
					</template>
					<template v-if="(field.compnent=='date')">
						<el-form-item :label="field.label">
						 	<el-checkbox-group v-model="field.value">
								<el-checkbox v-for="(id,name) in G_DimMap[field.relationModel]" 
						    		v-bind:label="id+''" ></el-checkbox>
							</el-checkbox-group>	
							<el-date-picker v-model="field.value" type="date" placeholder="选择日期" ></el-date-picker>
					  	</el-form-item>
					</template>
					<template v-if="(field.compnent=='select')">
						<el-form-item :label="field.label">
							<el-select v-model="field.value" clearable placeholder="请选择">
						    	<el-option v-for="(id,name) in G_DimMap[field.relationModel]" 
						    		:key="name" v-bind:label="id+''" :value="name">
						    	</el-option>
						  	</el-select>
					  	</el-form-item>
					</template>
					<template v-if="(field.compnent=='checkbox')">
						<el-form-item :label="field.label">
							<el-checkbox-group v-model="field.value">
								<el-checkbox v-for="(id,name) in G_DimMap[field.relationModel]" 
							    	v-bind:label="id" :key="name" v-bind:value="name">
						    	</el-checkbox>
					    	</el-checkbox-group>
					  	</el-form-item>
					</template>
				</template>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="true">
			<el-form label-width="120px">
				<template v-for="field in addTypeInfoForm">
					<template v-if="(field.compnent=='input')">
						<el-form-item :label="field.label"  >
							<el-input v-model="field.value" auto-complete="off"></el-input>
						</el-form-item>
					</template>
					<template v-if="(field.compnent=='date')">
						<el-form-item :label="field.label">
							<el-date-picker v-model="field.value" type="date" placeholder="选择日期" ></el-date-picker>
					  	</el-form-item>
					</template>
					<template v-if="(field.compnent=='select')">
						<el-form-item :label="field.label">
							<el-select v-model="field.value" clearable placeholder="请选择">
						    	<el-option v-for="(id,name) in G_DimMap[field.relationModel]" 
						    		:key="name" v-bind:label="id+''" :value="name">
						    	</el-option>
						  	</el-select>
					  	</el-form-item>
					</template>
					<template v-if="(field.compnent=='checkbox')">
						<el-form-item :label="field.label">
							<el-checkbox-group v-model="field.value">
								<el-checkbox v-for="(id,name) in G_DimMap[field.relationModel]" 
							    	v-bind:label="id" :key="name" v-bind:value="name">
						    	</el-checkbox>
					    	</el-checkbox-group>
					  	</el-form-item>
					</template>
					
				</template>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
	import { typeInfoJsonSync, listJson, createJson, allJSONSync, deleteJSON,showJSON, showJSONSync,updateJSON, batchDeleteJSON } from '../../api/PTcrudApi';


	export default {
		data() {
			
			/**
			 * 注意:应该在处输出进行部分数据结构的完成，例如：添加中select下拉框需要提前制定好数据格式form1.name下拉框中的对应关系会无效(又可调整点？)
			 *
			 */
			var G_data = {
					filters: {
						search: ''
					},
					total: 0,
					page: 1,
					listLoading: false,
					sels: [],//列表选中列
	
					editFormVisible: false,//编辑界面是否显示
					editLoading: false,
					editFormRules: {
						name: [
							{ required: true, message: '请输入姓名', trigger: 'blur' }
						]
					},
					addFormVisible: false,//新增界面是否显示
					addLoading: false,
	
					/**
					 * 核心数据
					 */
					G_DimMap: {} ,			// 字典数据 
					typeInfos: {}, 			// 字典模型结构
					addTypeInfoForm:[],		// 添加form数据
					updateTypeInfoForm:[],	// 更新的form数据
					datas: []				// 列表数据
					
					/**
					 * typeInfos示例：
					typeInfos:{
						"TripStartAddresses": [{
							"showName": "地点",
							"relationFields": [],
							"name": "addressName",
							"relationModel": "",
							"compnent": "input",
							"type": "text",
							"relationField": ""
						},
						{
							"showName": "描述",
							"relationFields": [],
							"name": "description",
							"relationModel": "",
							"compnent": "input",
							"type": "text",
							"relationField": ""
						},
						{
							"showName": "修改时间",
							"relationFields": [],
							"name": "_updateTime",
							"relationModel": "",
							"compnent": "",
							"type": "date",
							"relationField": ""
						}]
					}
					*/
				} ;
				
			return G_data ;
		},
		methods: {
			load_model_info: function( G_DimMap, typeInfos, addTypeInfoForm, updateTypeInfoForm ) {
				
				// 加载model
				let routeName = this.$route.name ;
				var typeInfoJsonRes = typeInfoJsonSync({
										type: routeName,
										params: {}
									}) ; 			
				// 主要model结构
				var modelName = routeName ;
				typeInfos[modelName]=typeInfoJsonRes.type ; 
				// console.info( "加载model结构完成"+JSON.stringify(typeInfoJsonRes) ) ;
				
				 
				// 获取关联modelName结构
				var modelFields = typeInfos[modelName]['fields'] ;
				for (var i=0; i<modelFields.length; i++ ) 
				{
					// 关联结构
					let modelField = modelFields[i] ;
					let modelFiled_RelationModel_name = modelField['relationModel'] ;
					let modelFiled_RelationModel_FieldName = modelField['relationField'] ;
					let modelFiled_RelationModel_FieldNames = modelField['relationFields'] ;
					if ( modelFiled_RelationModel_name!="" && modelFiled_RelationModel_name!=null && modelFiled_RelationModel_name!=undefined )
					{
						// 获取model的机构
						var relationModeTypeInfo = typeInfoJsonSync({
														type: modelFiled_RelationModel_name,
														params: {}
													});
						// console.info( JSON.stringify(relationModeTypeInfo) ) ;
						
						let relationModelFields = relationModeTypeInfo.type.fields ;
						typeInfos[modelFiled_RelationModel_name]=relationModeTypeInfo.type ;
						
						// 获取字典数据
						let relationModelAllData = allJSONSync({
														type: modelFiled_RelationModel_name,
														params: {}
													});
						var modelFiled_RelationModel_data = relationModelAllData.objects
						for( var j=0; j<modelFiled_RelationModel_data.length; j++ )
						{
							if ( G_DimMap[modelFiled_RelationModel_name] == undefined)
								G_DimMap[modelFiled_RelationModel_name] = new Object() ;	
							
							var fnames = ""
							fnames = modelFiled_RelationModel_data[j][modelFiled_RelationModel_FieldName] ;
							for( var c=0;c<modelFiled_RelationModel_FieldNames.length;c++ )
							{
								if ( c==0 ) fnames="" ;
								fnames += modelFiled_RelationModel_data[j][modelFiled_RelationModel_FieldNames[c]];
								if ( c!=(modelFiled_RelationModel_FieldNames.length-1) )
									fnames+="-|-" ;
							}
								
							G_DimMap[modelFiled_RelationModel_name][modelFiled_RelationModel_data[j]['id']] = fnames ;
							
						}
					}
				}
				console.info( "加载关联信息结构完成..."+JSON.stringify(typeInfos) ) ;
				 
			},
			switch_menu: function() {
				
				this.G_DimMap={} , 
				this.typeInfos={}, 
				this.datas=[]
				
				this.load_model_info( this.G_DimMap, this.typeInfos, this.addTypeInfoForm, this.updateTypeInfoForm ) ;
				this.getListDatas() ;
				 
				// console.info( "typeInfos->"+ JSON.stringify(G_data.typeInfos) ) ;
				// console.info( "addForm->"+JSON.stringify(G_data.addTypeInfoForm) ) ;
				// console.info( JSON.stringify(G_data.G_DimMap) ) ;
				// console.info( JSON.stringify(G_data.updateTypeInfoForm) ) ; 
			},
			//显示转换
			formatFun: function (row, column) {
				
				var arr = column.property.split("-") ;
				var fieldName = arr[0] ;
				var fieldValue = row[arr[1]] ;
				
				var valueStr = "" ;
				if ( (typeof fieldValue) == "string" ) {
					valueStr = this.G_DimMap[fieldName][fieldValue] ;
				}
				if ( (typeof fieldValue) == "number" ) {
				}
				if ( (typeof fieldValue) == "object" && (fieldValue instanceof Array)) {
					// console.info( "fieldValue->"+JSON.stringify(fieldValue) ) ;
					// console.info( "fieldName-val->"+JSON.stringify(this.G_DimMap[fieldName]))
					for( var i=0;i<fieldValue.length;i++ )
					{
						valueStr += this.G_DimMap[fieldName][fieldValue[i]]+"," ;
					}
					//console.info( "valueStr->"+valueStr ) ;
				}
				if ( (typeof fieldValue) == "object" && (fieldValue instanceof Function)) {
					console.info( "Function") ;
				}
				
				return valueStr;
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getListData();
			},
			//获取用户列表
			getListDatas() {

				let para = {
					type: this.$route.name,
					params: {
						page: this.page,
						search: this.filters.search
					}
				};
				this.listLoading = true;
				// NProgress.start();
				
				listJson(para).then((res) => {
					this.total = res.count;
					this.datas = res.objects;
					this.listLoading = false;
					// NProgress.done();
				});
				
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					deleteJSON({
						type: this.$route.name,
						params: {
							id: row.id 
						}
					}).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getListDatas();
					}).catch(() => {
					
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				
				this.editFormVisible = true; 
				let modelName = this.$route.name ;
				
				// 获取updateFrom表单显示需要的数据
				var res = showJSONSync({
					type: modelName,
					params: {
						id: row.id 
					}
				}) ;
				
				// 关联updateFrom表单结构
				var formFieldCount = 0 ; // 计算from有效的控件的数量
				this.updateTypeInfoForm=[] ;
				var modelFields = this.typeInfos[modelName]['fields'] ;
				for (var i=0; i<modelFields.length; i++ ){
					
					// 关联结构
					let modelField = modelFields[i] ;
					let modelFiled_RelationModel_name = modelField['relationModel'] ;
					let modelFiled_RelationModel_field = modelField['relationField'] ;
					let modelFiled_RelationModel_fields = modelField['relationFields'] ;
					// console.info( "modelFiled_RelationModel_fields->"+JSON.stringify(modelFiled_RelationModel_fields) ) ;
					
					if ( modelField['compnent']!=undefined && modelField['compnent'].length>0 )
					{
						if (this.updateTypeInfoForm[formFieldCount] ==null || this.updateTypeInfoForm[i] == undefined ) {
							this.updateTypeInfoForm[formFieldCount]={} ;
						}
						
						this.updateTypeInfoForm[formFieldCount]['label'] = modelField['showName'] ;
						this.updateTypeInfoForm[formFieldCount]['name'] = modelField['name'] ;
						this.updateTypeInfoForm[formFieldCount]['compnent'] = modelField['compnent'];
						if ( modelFiled_RelationModel_name!="" && modelFiled_RelationModel_name!=undefined && modelFiled_RelationModel_name.length>0 ) {
							this.updateTypeInfoForm[formFieldCount]['relationModel'] = modelFiled_RelationModel_name ;
						}
						this.updateTypeInfoForm[formFieldCount]['value'] = res.objects[this.updateTypeInfoForm[formFieldCount].name] ;
						if (modelField['compnent']=='checkbox')
						{
							var dimArry = res.objects[this.updateTypeInfoForm[formFieldCount].name] ;
							// console.info( "dimArray->"+JSON.stringify(dimArry) ) ;
							for( var ee=0;ee<dimArry.length; ee++ )
							{
								if( modelFiled_RelationModel_fields.length == 0 )
								{
									// console.info(modelFiled_RelationModel_field+"->"+dimArry[ee] ) ;
									this.updateTypeInfoForm[formFieldCount]['value'][ee] = this.G_DimMap[modelFiled_RelationModel_name][dimArry[ee]]; // dimArry[ee][modelFiled_RelationModel_field] ;
								}
								else
								{
									this.updateTypeInfoForm[formFieldCount]['value'][ee] = this.G_DimMap[modelFiled_RelationModel_name][dimArry[ee]] ;
								}
							}	
						}
						formFieldCount++;
					}
				}
                this.updateTypeInfoForm[formFieldCount] = {"label":"id","name":"id","compnent":"","value":res.objects['id']} ;

				this.listLoading = false;
				//NProgress.done();
				
				// FIXE 重新触发绑定,必须要这一句，不然页面控件无法接受更新
				this.updateTypeInfoForm = Object.assign({}, this.updateTypeInfoForm ) ;
				
				// console.info( JSON.stringify(this.updateTypeInfoForm) ) ;
			},
			//显示新增界面
			handleAdd: function () {
				
				this.addFormVisible = true;
								
				// 关联addform表单结构
				var modelName = this.$route.name ;
				var formFieldCount = 0 ; // 计算from有效的控件的数量

				this.addTypeInfoForm = [] ;
				var modelFields = this.typeInfos[modelName]['fields'] ;
				for (var i=0; i<modelFields.length; i++ ){
					
					// 关联结构
					let modelField = modelFields[i] ;
					let modelFiled_RelationModel_name = modelField['relationModel'] ;
					
					if ( modelField['compnent']!=undefined && modelField['compnent'].length>0 )
					{
						if ( this.addTypeInfoForm[formFieldCount] == undefined )
							this.addTypeInfoForm[formFieldCount]={} ;
						this.addTypeInfoForm[formFieldCount]['label'] = modelField['showName'] ;
						this.addTypeInfoForm[formFieldCount]['name'] = modelField['name'] ;
						this.addTypeInfoForm[formFieldCount]['compnent'] = modelField['compnent'];
						if ( modelFiled_RelationModel_name!="" && modelFiled_RelationModel_name!=undefined && modelFiled_RelationModel_name.length>0 ) {
							this.addTypeInfoForm[formFieldCount]['relationModel'] = modelFiled_RelationModel_name ;
						}
						this.addTypeInfoForm[formFieldCount]['value'] = '' ;
						if (modelField['compnent']=='checkbox')
							this.addTypeInfoForm[formFieldCount]['value'] = [] ;
						formFieldCount++;
					}
				}
				
				
				// FIXE 重新触发绑定,必须要这一句，不然页面控件无法接受更新
				this.addTypeInfoForm = Object.assign({}, this.addTypeInfoForm ) ;
				
				// console.info( JSON.stringify(this.addTypeInfoForm) ) ;
			},
			//编辑
			editSubmit: function () {
				
				this.$confirm('确认提交吗？', '提示', {}).then(() => {
					this.editLoading = true;
					//NProgress.start();
												
					// console.info( JSON.stringify(this.updateTypeInfoForm) ) ;
					var params = new Object() ;
					for( var i in this.updateTypeInfoForm )
					{
					
						if ( this.updateTypeInfoForm[i]["name"] == "id")
						{
							params["id"] = this.updateTypeInfoForm[i]["value"] ;
						}
						else
						{
							var values = this.updateTypeInfoForm[i]["value"] ;
							var relationModel = this.updateTypeInfoForm[i]["relationModel"] ;
							if ( relationModel!=undefined && (typeof values) == "object" && (values instanceof Array)) {
								var resVals = [] ;
								for( var j=0; j<values.length; j++ )
								{
									for( var val in this.G_DimMap[relationModel] )
									{
										if( this.G_DimMap[relationModel][val] == values[j] )
										{
											resVals[resVals.length]=val ;
										}
									}
								}
								
								if ( resVals.length == 0 ) resVals[0]="" ;
								params["object."+this.updateTypeInfoForm[i]["name"]+".id"] = resVals ;
							}
							else
							{
								params["object."+this.updateTypeInfoForm[i]["name"]] = this.updateTypeInfoForm[i]["value"] ;
							}
						}
					} 
					console.info( "params->"+JSON.stringify(params)) ;
					
					let para = {
						type: this.$route.name,
						params: params
					};
					
					updateJSON(para).then((res) => {
						this.editLoading = false;
						//NProgress.done();
						this.$message({
							message: '提交成功',
							type: 'success'
						});
						
						this.editFormVisible = false;
						this.getListDatas();
					});
				});
			},
			//新增
			addSubmit: function () {
				this.$confirm('确认提交吗？', '提示', {}).then(() => {
					this.addLoading = true;
					//NProgress.start();
					 
					var params = new Object() ;
					for( var i in this.addTypeInfoForm )
					{
						var values = this.addTypeInfoForm[i]["value"] ;
						var relationModel = this.addTypeInfoForm[i]["relationModel"] ;
						if ( relationModel!=undefined && (typeof values) == "object" && (values instanceof Array)) {
							var resVals = [] ;
							for( var j=0; j<values.length; j++ )
							{
								for( var val in this.G_DimMap[relationModel] )
								{
									if( this.G_DimMap[relationModel][val] == values[j] )
									{
										resVals[resVals.length]=val ;
									}
								}
							}
							params["object."+this.addTypeInfoForm[i]["name"]+".id"] = resVals ;
						}
						else
						{
							params["object."+this.addTypeInfoForm[i]["name"]] = this.addTypeInfoForm[i]["value"] ;
						}						
						
						// console.info( this.addTypeInfo[i]["name"] +":" + this.addTypeInfo[i]["value"] ) ;
					} 
					console.info( "AddSubmit->"+JSON.stringify(this.addTypeInfoForm)) ;
					
					let para = {
						type: this.$route.name,
						params: params
					};
					
					// console.info( params ) ;
					// para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
					
					createJson(para).then((res) => {
						this.addLoading = false;
						//NProgress.done();
						this.$message({
							message: '提交成功',
							type: 'success'
						});
						
						this.addFormVisible = false;
						this.getListDatas();
					});
					 
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				// console.info( ids ) ;
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					
					let para = {
						type: this.$route.name,
						params: {ids: ids}
					};
					
					batchDeleteJSON(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getListDatas();
					});

				}).catch(() => {

				});
			}
		},
		created () {
			this.switch_menu() ;	
		},
		mounted() {
			
		},
		watch: {
			'$route' (to, from) {
				this.switch_menu() ;
			}
		}
	}

</script>

<style scoped>

</style>